<?php

namespace App\Services;
use App\Models\Order;
use App\Models\WxPayRecord;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;

class EasyWeChatServices
{
    static function app(){
        $config = [
            'app_id' => config('wechat.wx_appid'),
            'secret' => config('wechat.wx_appsecret'),
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

        return Factory::officialAccount($config);

    }

    static function pay_app(){
        // 加载配置
        $config = [
           'app_id'    => 'wxb76f1734c33d9ef9',
           'mch_id'    => '1601648306',
           'sub_mch_id'    => '1608281782',
           'key'       => 'guangdongyinfeishukeyouxiangongs',
           'cert_path' => '1601648306_20201113_cert/apiclient_cert.pem',       //绝对路径的证书
           'key_path'  => '1601648306_20201113_cert/apiclient_key.pem',        //绝对路径的证书key
       ];

       return Factory::payment($config);
    }

    public function RefundedNotify($number,$refundNumber,$total_money,$refund_money,$refund_desc='非农行信用卡支付购券失败'){
        $order = Order::where('order_number',$number)->first();
        $wx_record = WxPayRecord::where('out_trade_no',$number)
            ->where('status',3)
            ->first();

        $pay_app = $this->pay_app();
        // 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
        // $pay_app->refund->byTransactionId(string $number, string $refundNumber, int $totalFee, int $refundFee, array $config = []);
        $result = $pay_app->refund->byOutTradeNumber($number,$refundNumber,$total_money,$refund_money, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => $refund_desc,
            // 'notify_url' => '银行卡不是ABC_CREDIT',
        ]);
        Log::info('退款数据--訂單號--'.$number.'---'.json_encode($result));

        if($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS' && $result['return_msg']=='OK'){
            //更改状态
            $order->order_status = 4;
            $order_result = $order->save();
            //更新流水订单
            $wx_record->status = 2;
            $wx_record->out_refund_no = $refundNumber;
            $wx_order_result = $wx_record->save();
            return true;
        }else{
            throw new \Exception('退款失敗');
            return false;
        }
    }
}